configurable = False
from common import *
from mig.csp2mig.client import *
import os
import shutil
import sys

def MiG_SubmitterFunc(context, in0, out0):
	initialized = False
	logs = []
	tempdir = None
	try:
		while True:
			mig_input = in0()
			# lazy initializtion. We don't know if we will ever be used...
			if not initialized:
				# create tempdir for this submitter
				initialized = True
				tempdir = tempfile.mkdtemp()
				if PRINT_DEBUG:
					print 'Submitter using temp folder: ' + tempdir	
				# send CSPBuilder to MiG if needed
				consider_copying_cspbuilder(tempdir)
			success = False
			try:
				client = Migclient()
				mig_output, success = client.run_job(mig_input, tempdir, context)
			except:
				print 'Submitter caught exception while running MiG job: ', sys.exc_info()
			finally:
				if success:
					logs.append(client.log)
					out0(mig_output)
				else:
					poison(in0)
					poison(out0)	
				
	finally:
		if initialized:
			shutil.rmtree(tempdir)
			if LOG_STATS:
				print_logs(logs)

